package com.his.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.his.admin.service.MedicineService;
import com.his.admin.service.OrderItemService;
import com.his.admin.service.OrderService;
import com.his.dao.domain.dto.AllMedicineDto;
import com.his.dao.domain.dto.ListDto;
import com.his.dao.domain.dto.MedicineListDto;
import com.his.dao.domain.dto.OrderDto;
import com.his.dao.domain.entity.Medicine;
import com.his.dao.domain.entity.Order;
import com.his.dao.domain.entity.OrderItem;
import com.his.dao.domain.vo.ListVo;
import com.his.dao.mapper.MedicineMapper;
import com.his.dao.mapper.OrderItemMapper;
import com.his.dao.mapper.OrderMapper;
import com.his.util.constant.RedisConstant;
import com.his.util.result.RestResult;
import com.his.util.result.RestResultBuilder;
import com.his.util.util.MapUtil;
import com.his.util.util.StringUtil;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import static com.his.util.constant.RedisConstant.getUserAndAuthorization;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author fall
 * @since 2022-11-28
 */
@Service
@AllArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    private RedisTemplate redisTemplate;
    private OrderMapper orderMapper;
    private OrderItemMapper orderItemMapper;
    private OrderItemService orderItemService;
    private MedicineMapper medicineMapper;
    private MedicineService medicineService;

    @Override
    public RestResult all(ListDto listDto) {
        OrderDto order = MapUtil.conversionMapToObj((LinkedHashMap) listDto.getObj(), OrderDto.class);

        return new RestResultBuilder().success(ListVo
                .builder()
                .list(orderMapper.selectAll(
                        order.getDoctorId(),
                        order.getPatientId(),
                        order.getHospitalId(),
                        listDto.getPage() * listDto.getPageSize(),
                        listDto.getPageSize()))
                .total(orderMapper.selectAllCount(
                        order.getDoctorId(),
                        order.getPatientId(),
                        order.getHospitalId()))
                .build());
    }

    @Override
    public RestResult allSave(String authorization, MedicineListDto medicineListDto) {
        int userId = StringUtil.getId(RedisConstant.USER, (String) redisTemplate.opsForValue().get(getUserAndAuthorization(authorization)));

        medicineListDto.setDoctorId(userId);
        save(medicineListDto);

        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>()
                .select("max(order_id) as orderId");

        Integer id = (Integer) getMap(queryWrapper).get("orderId");

        medicineListDto.setOrderId(id);

        List<OrderItem> list = new ArrayList<>();

        for (int i = 0;i < medicineListDto.getAllMedicine().size(); i++) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(medicineListDto.getOrderId());
            orderItem.setMedicineName(medicineListDto.getAllMedicine().get(i).getName());
            orderItem.setNumber(medicineListDto.getAllMedicine().get(i).getNumber());

            list.add(orderItem);
        }

        orderItemService.saveBatch(list);
        return new RestResultBuilder().success();
    }

    @Override
    public RestResult determine(Order orderId) {
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<OrderItem>()
                .eq("order_id", orderId.getOrderId());

        List<OrderItem> list = orderItemMapper.selectList(queryWrapper);

        List<Medicine> list1 = new ArrayList<>();
        for (OrderItem orderItem: list
             ) {
            QueryWrapper<Medicine> queryWrapper1 = new QueryWrapper<Medicine>()
                    .eq("name",orderItem.getMedicineName())
                    .ge("Inventory",orderItem.getNumber());
            Medicine medicine = medicineMapper.selectList(queryWrapper1).get(0);
            medicine.setInventory(medicine.getInventory() - orderItem.getNumber());

            list1.add(medicine);
        }

        medicineService.updateBatchById(list1);

        orderId.setState(1);
        orderMapper.updateById(orderId);
        return new RestResultBuilder().success();
    }
}
